﻿#include "logdialog.h"
#include "ui_logdialog.h"
#include <QMessageBox>
#include <QRegExp>
#include <QFile>
#include <QTextStream>

logDialog::logDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::logDialog)
{
    ui->setupUi(this);
    ui->labelImg->setScaledContents(true);
    this->resize(ui->labelImg->width(),ui->labelImg->height());
    ui->labelImg->move(0,0);
    setWindowTitle("驾考登录系统");
    setWindowFlags(Qt::Dialog|Qt::WindowCloseButtonHint);
}

logDialog::~logDialog()
{
    delete ui;
}


void logDialog::on_btnLog_clicked()
{
    QRegExp mail_user("^[a-zA-Z]\\w{5,17}@([A-Za-z0-9\\-]+\\.)+[A-Za-z]{2,6}$");
    bool res=mail_user.exactMatch(ui->userNameEdit->text());
    if(!res)//验证用户名格式
    {
        QMessageBox::information(this,"提示","非法的邮箱地址,请您重新输入!");
        ui->userNameEdit->clear();
        ui->passwordEdit->clear();
        ui->userNameEdit->setFocus();
        return;
    }
    else//验证用户密码
    {
        QString filename="../account.txt";
        QString username;
        QString passwd;
        QString strLine;
        QStringList strList;

        username=ui->userNameEdit->text();
        passwd=ui->passwordEdit->text();

        if(passwd.isEmpty())
        {
            QMessageBox::information(this,"提示","密码为空,请输入");
            ui->passwordEdit->setFocus();
            return ;
        }

        QFile file(filename);
        QTextStream stream(&file);

        if(file.open(QIODevice::ReadOnly|QIODevice::Text))
        {
            while(!stream.atEnd())
            {
                strLine=stream.readLine();
                strList=strLine.split(",");

                if(strList.count()!=2)
                {
                    //记录错误日志
                    continue;
                }

                if(username==strList.at(0))
                {
                    if(passwd==strList[1])
                    {
                        QMessageBox::information(this,"提示","欢迎尊敬的用户,登录成功!");
                        done(Accepted);
                        file.close();
                        return ;
                    }
                    else
                    {
                        QMessageBox::information(this,"提示","密码输入错误,请重新输入!");
                        ui->passwordEdit->clear();
                        ui->passwordEdit->setFocus();
                        file.close();
                        return ;
                    }
                }
                else
                {
                    continue;
                }

            }
            QMessageBox::information(this,"提示","你给输入的账户有误,请重新输入!");
            ui->userNameEdit->clear();
            ui->passwordEdit->clear();
            ui->userNameEdit->setFocus();
            file.close();
            return ;
        }
        else
        {
            QMessageBox::information(this,"提示","读取文件失败!");
        }

    }


}

void logDialog::on_btnCanal_clicked()
{
    done(Rejected);
}
